<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateStoreAPIRequest;
use App\Http\Requests\API\UpdateStoreAPIRequest;
use App\Models\Sells;
use App\Models\Store;
use App\Models\SellIssues;
use App\Repositories\StoreRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class StoreController
 * @package App\Http\Controllers\API
 */

class StoreAPIController extends AppBaseController
{
    /** @var  StoreRepository */
    private $storeRepository;

    public function __construct(StoreRepository $storeRepo)
    {
        $this->storeRepository = $storeRepo;
    }

    /**
     * Display a listing of the Store.
     * GET|HEAD /stores
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $park_arr = $this->getUserParks();
        $this->storeRepository->pushCriteria(new RequestCriteria($request));
        $this->storeRepository->pushCriteria(new LimitOffsetCriteria($request));
        $stores = $this->storeRepository->paginate($request->limit);
        $res = $stores->toArray();
        foreach ($res['data'] as &$v) {
            $v['money'] = (isset($v['money'])&&!empty($v['money']))?re2float($v['money']/100):'0.00';
            $v['park_list'] = explode(",",$v['park_ids']);
            $pk = [];
            foreach ($v['park_list'] as $val) {
                $pk[] = $park_arr[$val]??'';
            }
            $v['park_name'] = trim(implode(",",$pk),',');
            $v['vpl_num'] = SellIssues::where("store_id",$v['id'])->count();
        }

        return $this->sendResponse($res, '获取成功');
    }

    /**
     * Store a newly created Store in storage.
     * POST /stores
     *
     * @param CreateStoreAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateStoreAPIRequest $request)
    {
        $input = $request->all();
        if(isset($input['money']) && !empty($input['money'])){
            $input['money'] = $input['money']*100;
        }
        $stores = $this->storeRepository->create($input);

        return $this->sendResponse($stores->toArray(), '保存成功');
    }

    /**
     * Display the specified Store.
     * GET|HEAD /stores/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $park_arr = $this->getUserParks();
        /** @var Store $store */
        $store = $this->storeRepository->findWithoutFail($id);

        if (empty($store)) {
            return $this->sendError('没有此数据');
        }
        $store->money = $store->money/100;
        $store->vpl_num = SellIssues::where("store_id",$store->id)->count();

        $store->park_list = explode(",", $store->park_ids);
        if($store->park_list) {
            $pk = [];
            foreach ($store->park_list as $val) {
                $pk[] = $park_arr[$val]??'';
            }
            $store->park_names = $pk;
        } else {
            $store->park_list = [];
            $store->park_names = [];
        }
        return $this->sendResponse($store->toArray(), '获取成功');
    }

    /**
     * Update the specified Store in storage.
     * PUT/PATCH /stores/{id}
     *
     * @param  int $id
     * @param UpdateStoreAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateStoreAPIRequest $request)
    {
        $input = $request->all();
        if(isset($input['money']) && !empty($input['money'])){
            $input['money'] = $input['money']*100;
        }
        /** @var Store $store */
        $store = $this->storeRepository->findWithoutFail($id);

        if (empty($store)) {
            return $this->sendError('没有此数据');
        }
        $input['vpl_status'] = 2;
        if(isset($input['fee_type']) && $input['fee_type'] == 1){
            $input['settle_time'] = date("Y-m-d H:i:s");
        } else {
            $settime = $input['settle_period']??0;
            $input['settle_time'] = date("Y-m-d H:i:s",strtotime("+$settime months"));
        }
        $store = $this->storeRepository->update($input, $id);
        if($store){
            $sell = $this->storeRepository->findWithoutFail($id);
            $sell = obj2arr($sell);
            unset($sell['id']);
            Sells::create($sell);
        }

        return $this->sendResponse($store->toArray(), '操作成功');
    }

    /**
     * Update the specified Store in storage.
     * PUT/PATCH /stores/{id}
     *
     * @param  int $id
     * @param UpdateStoreAPIRequest $request
     *
     * @return Response
     */
    public function flag(Request $request)
    {
        $input = $request->all();
        if (isset($input['id']) && empty($input['id'])) {
            return $this->sendError('缺少id');
        }
        $id = $input['id'];
        /** @var Store $store */
        $store = $this->storeRepository->findWithoutFail($id);

        if (empty($store)) {
            return $this->sendError('没有此数据');
        }

        $store = $this->storeRepository->update($input, $id);

        return $this->sendResponse($store->toArray(), '操作成功');
    }

    /**
     * Remove the specified Store from storage.
     * DELETE /stores/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var Store $store */
        $store = $this->storeRepository->findWithoutFail($id);

        if (empty($store)) {
            return $this->sendError('没有此数据');
        }
        $num = SellIssues::where("store_id",$id)->count();
        if($num){
            return $this->sendError('此商户存在于预售授权数据中，无法删除');
        }
        $store->delete();

        return $this->sendResponse($id, '操作成功');
    }
}
